import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:intl/intl.dart';
import 'dart:developer' as developer;

class WeatherTest extends StatefulWidget {
  const WeatherTest({super.key});

  @override
  State<WeatherTest> createState() => _WeatherTestState();
}

class _WeatherTestState extends State<WeatherTest> {
  bool _isLoading = true;
  Map<String, dynamic>? _weatherData;
  String? _errorMessage;
  
  // 彩云天气 API Key
  final String _apiKey = 'VPc24KcG9gjyUZLk';
  
  // 默认使用北京的坐标 (经度,纬度)
  final String _defaultLocation = '116.4074,39.9042'; // 北京
  final String _cityName = "北京";
  
  // 天气图标映射
  final Map<String, IconData> _weatherIcons = {
    'CLEAR_DAY': Icons.wb_sunny,
    'CLEAR_NIGHT': Icons.nights_stay,
    'PARTLY_CLOUDY_DAY': Icons.wb_cloudy,
    'PARTLY_CLOUDY_NIGHT': Icons.cloud_queue,
    'CLOUDY': Icons.cloud,
    'LIGHT_HAZE': Icons.blur_on,
    'MODERATE_HAZE': Icons.blur_on,
    'HEAVY_HAZE': Icons.blur_circular,
    'LIGHT_RAIN': Icons.grain,
    'MODERATE_RAIN': Icons.beach_access,
    'HEAVY_RAIN': Icons.water,
    'STORM_RAIN': Icons.thunderstorm,
    'FOG': Icons.cloud,
    'LIGHT_SNOW': Icons.ac_unit,
    'MODERATE_SNOW': Icons.ac_unit,
    'HEAVY_SNOW': Icons.ac_unit,
    'STORM_SNOW': Icons.ac_unit,
    'DUST': Icons.blur_circular,
    'SAND': Icons.blur_circular,
    'WIND': Icons.air,
  };
  
  // 天气现象中文描述
  final Map<String, String> _weatherDescriptions = {
    'CLEAR_DAY': '晴天',
    'CLEAR_NIGHT': '晴夜',
    'PARTLY_CLOUDY_DAY': '多云',
    'PARTLY_CLOUDY_NIGHT': '多云',
    'CLOUDY': '阴',
    'LIGHT_HAZE': '轻度雾霾',
    'MODERATE_HAZE': '中度雾霾',
    'HEAVY_HAZE': '重度雾霾',
    'LIGHT_RAIN': '小雨',
    'MODERATE_RAIN': '中雨',
    'HEAVY_RAIN': '大雨',
    'STORM_RAIN': '暴雨',
    'FOG': '雾',
    'LIGHT_SNOW': '小雪',
    'MODERATE_SNOW': '中雪',
    'HEAVY_SNOW': '大雪',
    'STORM_SNOW': '暴雪',
    'DUST': '浮尘',
    'SAND': '沙尘',
    'WIND': '大风',
  };
  
  @override
  void initState() {
    super.initState();
    developer.log('HomePage初始化');
    _getWeatherData(_defaultLocation);
  }
  
  // 获取天气数据
  Future<void> _getWeatherData(String location) async {
    try {
      setState(() {
        _isLoading = true;
        _errorMessage = null;
      });
      
      final apiUrl = 'https://api.caiyunapp.com/v2.6/$_apiKey/$location/realtime';
      developer.log('开始发送彩云天气API请求: $apiUrl');
      
      final response = await http.get(Uri.parse(apiUrl));
      
      developer.log('API响应状态码: ${response.statusCode}');
      developer.log('API响应体: ${response.body}');
      
      if (response.statusCode == 200) {
        developer.log('API请求成功，开始解析数据');
        final jsonData = json.decode(response.body);
        
        if (jsonData['status'] == 'ok') {
          developer.log('数据解析成功: ${jsonData['result'] != null ? '包含result数据' : '缺少result数据'}');
          
          setState(() {
            _weatherData = jsonData;
            _isLoading = false;
          });
          developer.log('天气数据已更新到UI');
        } else {
          developer.log('API返回状态不是ok: ${jsonData['status']}');
          _setError('获取天气数据失败: ${jsonData['status']}');
        }
      } else {
        developer.log('API请求失败，状态码: ${response.statusCode}，响应体: ${response.body}', error: response.body);
        _setError('获取天气数据失败: ${response.statusCode}');
      }
    } catch (e, stackTrace) {
      developer.log('API请求发生异常', error: e.toString(), stackTrace: stackTrace);
      _setError('API请求错误: $e');
    }
  }
  
  void _setError(String message) {
    developer.log('设置错误信息: $message');
    setState(() {
      _errorMessage = message;
      _isLoading = false;
    });
    Fluttertoast.showToast(
      msg: message,
      toastLength: Toast.LENGTH_LONG,
      gravity: ToastGravity.BOTTOM,
    );
    developer.log('已显示Toast错误消息');
  }
  
  // 刷新天气数据
  Future<void> _refreshWeatherData() async {
    developer.log('开始刷新天气数据');
    await _getWeatherData(_defaultLocation);
  }
  
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        decoration: BoxDecoration(
          gradient: LinearGradient(
            begin: Alignment.topCenter,
            end: Alignment.bottomCenter,
            colors: [
              const Color(0xFF60C3FF),
              const Color(0xFF60C3FF).withOpacity(0.7),
            ],
          ),
        ),
        child: SafeArea(
          child: _isLoading 
            ? _buildLoadingView() 
            : (_errorMessage != null 
                ? _buildErrorView() 
                : _buildWeatherView()),
        ),
      ),
    );
  }
  
  Widget _buildLoadingView() {
    return const Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          CircularProgressIndicator(
            color: Colors.white,
          ),
          SizedBox(height: 20),
          Text(
            '正在获取天气数据...',
            style: TextStyle(color: Colors.white),
          ),
        ],
      ),
    );
  }
  
  Widget _buildErrorView() {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          const Icon(
            Icons.error_outline,
            color: Colors.white,
            size: 60,
          ),
          SizedBox(height: 16.h),
          Text(
            _errorMessage ?? '未知错误',
            style: GoogleFonts.racingSansOne(
              fontSize: 16.sp,
              color: Colors.white,
            ),
            textAlign: TextAlign.center,
          ),
          SizedBox(height: 24.h),
          ElevatedButton(
            onPressed: _refreshWeatherData,
            style: ElevatedButton.styleFrom(
              backgroundColor: Colors.white,
              foregroundColor: const Color(0xFF60C3FF),
            ),
            child: const Text('重试'),
          ),
        ],
      ),
    );
  }
  
  Widget _buildWeatherView() {
    if (_weatherData == null) {
      developer.log('天气数据为空，无法构建视图');
      return const SizedBox();
    }
    
    try {
      developer.log('开始构建天气视图');
      
      final realtime = _weatherData!['result']['realtime'];
      
      developer.log('成功获取realtime数据');
      
      // 获取当前温度
      final temp = realtime['temperature'].toString();
      
      // 获取天气现象
      final skycon = realtime['skycon'] as String;
      final weatherDescription = _weatherDescriptions[skycon] ?? skycon;
      
      // 获取当前时间
      final DateTime now = DateTime.now();
      final String formattedDate = DateFormat('EEEE, d MMMM', 'zh_CN').format(now);
      final String formattedTime = DateFormat('HH:mm').format(now);
      
      developer.log('日期格式化完成: $formattedDate, $formattedTime');
      
      return RefreshIndicator(
        onRefresh: _refreshWeatherData,
        child: ListView(
          padding: EdgeInsets.symmetric(horizontal: 20.w),
          children: [
            SizedBox(height: 20.h),
            
            // 位置和日期
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      _cityName,
                      style: GoogleFonts.racingSansOne(
                        fontSize: 16.sp,
                        color: Colors.white,
                      ),
                    ),
                    Text(
                      formattedDate,
                      style: GoogleFonts.racingSansOne(
                        fontSize: 14.sp,
                        color: Colors.white.withOpacity(0.8),
                      ),
                    ),
                  ],
                ),
                Text(
                  formattedTime,
                  style: GoogleFonts.racingSansOne(
                    fontSize: 24.sp,
                    color: Colors.white,
                  ),
                ),
              ],
            ),
            
            SizedBox(height: 40.h),
            
            // 当前天气
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      '$temp°C',
                      style: GoogleFonts.racingSansOne(
                        fontSize: 64.sp,
                        color: Colors.white,
                      ),
                    ),
                    Text(
                      weatherDescription,
                      style: GoogleFonts.racingSansOne(
                        fontSize: 16.sp,
                        color: Colors.white,
                      ),
                    ),
                    SizedBox(height: 8.h),
                    Text(
                      '体感温度: ${realtime['apparent_temperature']}°C',
                      style: GoogleFonts.racingSansOne(
                        fontSize: 14.sp,
                        color: Colors.white.withOpacity(0.8),
                      ),
                    ),
                  ],
                ),
                Icon(
                  _weatherIcons[skycon] ?? Icons.help_outline,
                  size: 100.w,
                  color: Colors.white,
                ),
              ],
            ),
            
            SizedBox(height: 40.h),
            
            // 其他天气信息
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceAround,
              children: [
                _buildWeatherInfo(
                  '湿度',
                  '${(realtime['humidity'] * 100).toStringAsFixed(0)}%',
                  Icons.water_drop_outlined,
                ),
                _buildWeatherInfo(
                  '风速',
                  '${realtime['wind']['speed']} m/s',
                  Icons.air,
                ),
                _buildWeatherInfo(
                  '气压',
                  '${(realtime['pressure'] / 100).toStringAsFixed(0)} hPa',
                  Icons.compress,
                ),
              ],
            ),
            
            SizedBox(height: 20.h),
            
            // 更多天气信息
            Container(
              padding: EdgeInsets.all(16.w),
              decoration: BoxDecoration(
                color: Colors.white.withOpacity(0.2),
                borderRadius: BorderRadius.circular(16.r),
              ),
              child: Column(
                children: [
                  Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      _buildWeatherInfo(
                        '能见度',
                        '${realtime['visibility']} km',
                        Icons.visibility,
                      ),
                      _buildWeatherInfo(
                        '云量',
                        '${(realtime['cloudrate'] * 100).toStringAsFixed(0)}%',
                        Icons.cloud_outlined,
                      ),
                      _buildWeatherInfo(
                        '风向',
                        '${_getWindDirection(realtime['wind']['direction'])}',
                        Icons.navigation,
                      ),
                    ],
                  ),
                  SizedBox(height: 16.h),
                  Row(
                    mainAxisAlignment: MainAxisAlignment.spaceAround,
                    children: [
                      _buildPrecipitationInfo(realtime['precipitation']),
                    ],
                  ),
                ],
              ),
            ),
            
            SizedBox(height: 20.h),
            
            // 空气质量
            Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  '空气质量',
                  style: GoogleFonts.racingSansOne(
                    fontSize: 18.sp,
                    color: Colors.white,
                  ),
                ),
                SizedBox(height: 16.h),
                Container(
                  padding: EdgeInsets.all(16.w),
                  decoration: BoxDecoration(
                    color: Colors.white.withOpacity(0.2),
                    borderRadius: BorderRadius.circular(16.r),
                  ),
                  child: Column(
                    children: [
                      Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: [
                          _buildAirQualityItem(
                            'AQI',
                            realtime['air_quality']['aqi']['chn'].toString(),
                            realtime['air_quality']['description']['chn'],
                          ),
                          _buildAirQualityItem(
                            'PM2.5',
                            realtime['air_quality']['pm25'].toString(),
                            'μg/m³',
                          ),
                          _buildAirQualityItem(
                            'PM10',
                            realtime['air_quality']['pm10'].toString(),
                            'μg/m³',
                          ),
                        ],
                      ),
                      SizedBox(height: 16.h),
                      Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: [
                          _buildAirQualityItem(
                            'NO₂',
                            realtime['air_quality']['no2'].toString(),
                            'μg/m³',
                          ),
                          _buildAirQualityItem(
                            'SO₂',
                            realtime['air_quality']['so2'].toString(),
                            'μg/m³',
                          ),
                          _buildAirQualityItem(
                            'O₃',
                            realtime['air_quality']['o3'].toString(),
                            'μg/m³',
                          ),
                        ],
                      ),
                      SizedBox(height: 16.h),
                      _buildAirQualityItem(
                        'CO',
                        realtime['air_quality']['co'].toString(),
                        'mg/m³',
                      ),
                    ],
                  ),
                ),
              ],
            ),
            
            SizedBox(height: 30.h),
            
            // 生活指数
            Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  '生活指数',
                  style: GoogleFonts.racingSansOne(
                    fontSize: 18.sp,
                    color: Colors.white,
                  ),
                ),
                SizedBox(height: 16.h),
                Container(
                  padding: EdgeInsets.all(16.w),
                  decoration: BoxDecoration(
                    color: Colors.white.withOpacity(0.2),
                    borderRadius: BorderRadius.circular(16.r),
                  ),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceAround,
                    children: [
                      _buildLifeIndexItem(
                        '舒适度',
                        realtime['life_index']['comfort']['desc'],
                        Icons.sentiment_satisfied_alt,
                      ),
                      _buildLifeIndexItem(
                        '紫外线',
                        realtime['life_index']['ultraviolet']['desc'],
                        Icons.wb_sunny_outlined,
                      ),
                    ],
                  ),
                ),
              ],
            ),
            
            SizedBox(height: 20.h),
            
            // 数据来源
            Center(
              child: Text(
                '数据来源: 彩云天气',
                style: GoogleFonts.racingSansOne(
                  fontSize: 12.sp,
                  color: Colors.white.withOpacity(0.6),
                ),
              ),
            ),
            
            SizedBox(height: 20.h),
          ],
        ),
      );
    } catch (e, stackTrace) {
      developer.log('构建天气视图时发生错误', error: e.toString(), stackTrace: stackTrace);
      return Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            const Icon(Icons.error_outline, color: Colors.white, size: 60),
            const SizedBox(height: 20),
            Text(
              '数据解析错误: $e',
              style: const TextStyle(color: Colors.white),
              textAlign: TextAlign.center,
            ),
            const SizedBox(height: 20),
            ElevatedButton(
              onPressed: _refreshWeatherData,
              style: ElevatedButton.styleFrom(
                backgroundColor: Colors.white,
                foregroundColor: const Color(0xFF60C3FF),
              ),
              child: const Text('重试'),
            ),
          ],
        ),
      );
    }
  }
  
  String _getWindDirection(double direction) {
    const List<String> directions = ['北', '东北', '东', '东南', '南', '西南', '西', '西北', '北'];
    final index = ((direction + 22.5) % 360) ~/ 45;
    return directions[index];
  }
  
  Widget _buildPrecipitationInfo(Map<String, dynamic> precipitation) {
    final local = precipitation['local']['intensity'];
    final nearest = precipitation['nearest'];
    
    String message;
    IconData icon;
    
    if (local > 0) {
      message = '当前降水强度: ${local.toStringAsFixed(2)} mm/h';
      icon = Icons.umbrella;
    } else if (nearest['distance'] < 10000) {
      message = '${(nearest['distance'] / 1000).toStringAsFixed(1)}km 外有降水';
      icon = Icons.water_drop_outlined;
    } else {
      message = '附近无降水';
      icon = Icons.wb_sunny_outlined;
    }
    
    return Column(
      children: [
        Icon(
          icon,
          color: Colors.white,
          size: 24.sp,
        ),
        SizedBox(height: 8.h),
        Text(
          '降水信息',
          style: GoogleFonts.racingSansOne(
            fontSize: 14.sp,
            color: Colors.white.withOpacity(0.8),
          ),
        ),
        SizedBox(height: 4.h),
        Text(
          message,
          style: GoogleFonts.racingSansOne(
            fontSize: 16.sp,
            color: Colors.white,
          ),
        ),
      ],
    );
  }
  
  Widget _buildWeatherInfo(String title, String value, IconData icon) {
    return Column(
      children: [
        Icon(
          icon,
          color: Colors.white,
          size: 24.sp,
        ),
        SizedBox(height: 8.h),
        Text(
          title,
          style: GoogleFonts.racingSansOne(
            fontSize: 14.sp,
            color: Colors.white.withOpacity(0.8),
          ),
        ),
        SizedBox(height: 4.h),
        Text(
          value,
          style: GoogleFonts.racingSansOne(
            fontSize: 16.sp,
            color: Colors.white,
          ),
        ),
      ],
    );
  }
  
  Widget _buildAirQualityItem(String title, String value, String unit) {
    return Column(
      children: [
        Text(
          title,
          style: GoogleFonts.racingSansOne(
            fontSize: 14.sp,
            color: Colors.white.withOpacity(0.8),
          ),
        ),
        SizedBox(height: 4.h),
        Text(
          value,
          style: GoogleFonts.racingSansOne(
            fontSize: 18.sp,
            color: Colors.white,
          ),
        ),
        Text(
          unit,
          style: GoogleFonts.racingSansOne(
            fontSize: 12.sp,
            color: Colors.white.withOpacity(0.8),
          ),
        ),
      ],
    );
  }
  
  Widget _buildLifeIndexItem(String title, String value, IconData icon) {
    return Column(
      children: [
        Icon(
          icon,
          color: Colors.white,
          size: 24.sp,
        ),
        SizedBox(height: 8.h),
        Text(
          title,
          style: GoogleFonts.racingSansOne(
            fontSize: 14.sp,
            color: Colors.white.withOpacity(0.8),
          ),
        ),
        SizedBox(height: 4.h),
        Text(
          value,
          style: GoogleFonts.racingSansOne(
            fontSize: 16.sp,
            color: Colors.white,
          ),
        ),
      ],
    );
  }
}